<template>
    <div class="left-center-card">
        <CategorySelect class="left-center-card-category-select"></CategorySelect>
        <BaseECharts ref="echartsRef" height="300px"></BaseECharts>
    </div>
</template>

<script setup lang="ts">
import type { ECOption } from '@/components/baseECharts/config'
import { BaseEchartsType } from '@/components/baseECharts/type'
import { ZRColor } from '@/types/echarts'

const echartsRef = ref<BaseEchartsType>()
const nameList = ['Scss', 'Html', 'Ts', 'Js', 'Vue', 'React', 'Axios', 'Vite', 'Npm', 'Pnpm']
// 配置中心（便于维护）
const CONFIG = {
    colors: {
        top3: [
            {
                x: 0,
                y: 1,
                x2: 1,
                y2: 1,
                colorStops: [
                    { offset: 0, color: '#EB3B5A' },
                    { offset: 1, color: '#FE9C5A' },
                ],
            },
            {
                x: 0,
                y: 1,
                x2: 1,
                y2: 1,
                colorStops: [
                    { offset: 0, color: '#FA8231' },
                    { offset: 1, color: '#FFD14C' },
                ],
            },
            {
                x: 0,
                y: 1,
                x2: 1,
                y2: 1,
                colorStops: [
                    { offset: 0, color: '#F7B731' },
                    { offset: 1, color: '#FFEE96' },
                ],
            },
        ], // 渐变红/金/科技蓝
        default: {
            x: 0,
            y: 1,
            x2: 1,
            y2: 1,
            colorStops: [
                { offset: 0, color: '#395CFE' },
                { offset: 1, color: '#2EC7CF' },
            ],
        },
    },
    maxItems: 9, // 显示的最大柱数
    topN: 3, // 需要特殊标记的名次
}
type BarDataItem = {
    name: string
    value: number
    itemStyle: { color: ZRColor }
    label?: { show: boolean }
}
const data: BarDataItem[] = nameList.map((item) => {
    return { name: item, value: Math.round(Math.random() * 100), itemStyle: { color: CONFIG.colors.default } }
})
onMounted(() => {
    updateColors()
    setOption(data)
})
setInterval(() => {
    update()
}, 2000)

const setOption = (data: BarDataItem[]) => {
    const options: ECOption = {
        graphic: [
            // 自定义左上角标题
            {
                type: 'group',
                children: (() => {
                    const img = new URL('../../../images/title-box-1.png', import.meta.url).href
                    const width = 127
                    const height = 39
                    const title = '品牌占有率'
                    return [
                        {
                            type: 'text',
                            style: {
                                align: 'center',
                                verticalAlign: 'middle',
                                text: title,
                                width: width,
                                height: height,
                                lineHeight: height,
                                x: width / 2,
                                y: height / 2,
                                fontSize: 18,
                                fontWeight: 'bold',
                                fill: '#fff',
                                backgroundColor: {
                                    image: img,
                                },
                                textShadowBlur: 20,
                                textShadowColor: '#fff',
                            },
                        },
                    ]
                })(),
            },
        ],
        grid: {
            top: '20%',
            left: '3%',
            right: '5%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'value',
            splitLine: { show: false },
            axisLabel: { show: false },
            axisTick: { show: false },
            axisLine: { show: false },
        },
        yAxis: [
            {
                type: 'category',
                axisLabel: { color: '#fff' },
                data: nameList,
                inverse: true,
                animationDuration: 300,
                animationDurationUpdate: 300,
                max: CONFIG.maxItems,
                splitLine: { show: false },
                axisTick: { show: false },
                axisLine: { show: false },
            },
            {
                axisLabel: { color: '#fff' },
                data: data.map((item) => item.value),
                inverse: true,
                animationDuration: 300,
                animationDurationUpdate: 300,
                max: CONFIG.maxItems,
                splitLine: { show: false },
                axisTick: { show: false },
                axisLine: { show: false },
            },
        ],
        series: [
            // 柱状图
            {
                name: 'barName',
                type: 'bar',
                barWidth: 10,
                realtimeSort: true,
                showBackground: true,
                animationDuration: 300,
                animationDurationUpdate: 300,
                backgroundStyle: {
                    color: '#173f8e',
                    borderRadius: 10,
                },
                itemStyle: {
                    borderRadius: 10,
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 16,
                        fontWeight: 'bold',
                        align: 'center',
                        verticalAlign: 'middle',
                        color: '#fff',
                        position: 'insideRight',
                        valueAnimation: true,
                        width: 48,
                        height: 33,
                        lineHeight: 33,
                        backgroundColor: {
                            image: new URL('../../../images/tooltip-1.png', import.meta.url).href,
                        },
                        offset: [-20, -20],
                    },
                },
                data: data,
            },
        ],
        animationDuration: 0,
        animationDurationUpdate: 2000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear',
    }
    echartsRef.value?.setOption(options)
}

const update = () => {
    data.forEach((item) => {
        item.value += Math.random() > 0.9 ? Math.round(Math.random() * 1000) : Math.round(Math.random() * 10)
    })
    updateColors()
    echartsRef.value?.setOption({ series: [{ data: data }] })
}
const updateColors = () => {
    // 深拷贝排序（保留原始索引）
    const sorted = [...data].map((item, index) => ({ ...item, originalIndex: index })).sort((a, b) => b.value - a.value) // 重置所有颜色
    // 重置所有为默认色
    data.forEach((item) => (item.itemStyle.color = CONFIG.colors.default))

    sorted.slice(0, CONFIG.topN).forEach((item, rank) => {
        if (item.value > 0) {
            // 过滤无效值
            data[item.originalIndex].itemStyle.color = CONFIG.colors.top3[Math.min(rank, CONFIG.colors.top3.length - 1)]
        }
    })
}
</script>

<style lang="scss" scoped>
.left-center-card {
    position: relative;
    height: 300px;

    .left-center-card-category-select {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 99;
    }
}
</style>
